<script lang="ts" setup name="MenuSortModal">
import { ref } from 'vue'
import { menuApi } from '@/MainApp/apis/menu'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  menuTree: {
    type: Array<any>,
    default: () => []
  }
})
const emits = defineEmits<{
  (e: 'cancel', visible: boolean): void
  (e: 'confirm'): void
}>()
const { t, dialog } = useConfig()
const { msgSuccess, msgError } = useMessage()
const dVisible = ref(false)
const loading = ref(false)

watch(
  () => props.visible,
  val => {
    dVisible.value = val
  }
)
const defaultExpanded: any[] = [] // computed(() => [props.menuTree[0].id])
// 新增、修改
const handConfirm = () => {
  emits('confirm')
}
// 保存排序
const handSortMenu = async (param: {
  currentOrder: Number
  parentId: Number
  targetOrder: Number
  targetParentId: Number
  position: string
  currentId: string
  targetId: string
}) => {
  const { success, msg } = await menuApi.toSortMenu(param)
  if (success) {
    msgSuccess(msg)
    handConfirm()
  }
  else {
    // dVisible.value = false
    msgError(msg)
  }
}

const handClosed = () => {
  dVisible.value = false
  emits('cancel', false)
}
const handleNodeDrop = async (oldNode: { data: { sortOrder: any; parentId: any; id: any; }; }, newNode: { data: { sortOrder: any; parentId: any; id: any; }; }, loc: string) => {
  const params = {
    currentOrder: oldNode.data.sortOrder,
    parentId: oldNode.data.parentId,
    targetOrder: newNode.data.sortOrder,
    targetParentId: newNode.data.parentId,
    position: loc.toUpperCase(),
    currentId: oldNode.data.id,
    targetId: newNode.data.id
  }
  await handSortMenu(params)
}
</script>

<template>
  <el-dialog
    v-model="dVisible"
    title="菜单排序"
    :width="dialog.sl"
    draggable
    :close-on-click-modal="false"
    align-center
    @closed="handClosed"
  >
    <el-alert
      title="请拖拽菜单、按钮排序"
      type="info"
      class="!mb-[16px]"
      :closable="false"
    />
    <el-row>
      <el-col :span="24">
        <el-tree
          v-loading="loading"
          :default-expanded-keys="defaultExpanded"
          node-key="id"
          :expand-on-click-node="false"
          :data="props.menuTree"
          :props="{
            children: 'children',
            label: 'name',
          }"
          draggable
          @node-drop="handleNodeDrop"
        />
      </el-col>
    </el-row>
    <template #footer>
      <!-- <el-button @click="handClosed">
        {{ t('action.cancel') }}
      </el-button> -->
      <el-button :loading="loading" @click="handClosed">
        {{ t('action.close') }}
      </el-button>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
:deep(.el-tree-node__content) {
  height: 30px;
  cursor: move;
  font-size: 16px;
}
</style>
